package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderFeignClient orderFeignClient;

    //查询秒杀所有商品
    @GetMapping("findAll")
    public Result findAll(){
        List<SeckillGoods> seckillGoodsList = this.seckillGoodsService.findAll();
        return Result.ok(seckillGoodsList);
    }
    //查询秒杀商品详情
    @GetMapping("getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId){
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoods(skuId);
        return Result.ok(seckillGoods);
    }

    //抢购码
    @GetMapping("auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        //获取userId
        String userId = AuthContextHolder.getUserId(request);
        //在秒杀开始以后   结束之前
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoods(skuId);
        if (seckillGoods!=null){
            //当前时间
            Date currentTime = new Date();
            //判断  比较时间大小
            if (DateUtil.dateCompare(seckillGoods.getStartTime(),currentTime) && DateUtil.dateCompare(currentTime,seckillGoods.getEndTime())){
                //生成抢购码
                String skuIdStr = MD5.encrypt(userId);
                return Result.ok(skuIdStr);
            }
        }
        return Result.fail().message("生成抢购码失败");
    }
    //预下单
    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId,HttpServletRequest request){
        //获取抢购码
        String skuIdStr = request.getParameter("skuIdStr");
        String userId = AuthContextHolder.getUserId(request);


        return this.seckillGoodsService.seckillOrder(skuId,skuIdStr,userId);
    }

    @GetMapping("auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        /**
         * 1.验证缓存中是否有用户Id
         * 2.判断用户是否有预下单  有-->抢购成功 去下单
         * 3.判断用户是否真正下过订单  --> 抢购成功 我的订单
         * 4.校验一下状态位
         */
        //获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        return this.seckillGoodsService.checkOrder(skuId,userId);
    }

    //秒杀结算页
    @GetMapping("/auth/trade")
    public Result authTrade(HttpServletRequest request){
        HashMap<String, Object> hashMap = new HashMap<>();
        String userId = AuthContextHolder.getUserId(request);
        //远程调用收货地址列表
        List<UserAddress> userAddressList = this.userFeignClient.findUserAddressListByUserId(userId);
        //获取订单明细  从预下单数据获取
        OrderRecode orderRecode = (OrderRecode) this.redisTemplate.opsForHash().get(RedisConst.SECKILL_ORDERS, userId);
        //判断
        if (orderRecode==null){
            return Result.fail().message("获取预下单数据失败");
        }
        //获取到秒杀商品
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();
        //赋值给订单明细
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuId(seckillGoods.getSkuId());
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setSkuNum(orderRecode.getNum());
        ArrayList<OrderDetail> detailArrayList = new ArrayList<>();
        detailArrayList.add(orderDetail);

        hashMap.put("userAddressList",userAddressList);
        hashMap.put("detailArrayList",detailArrayList);
        hashMap.put("totalAmount",orderDetail.getOrderPrice());
        hashMap.put("totalNum",1);

        return Result.ok(hashMap);
    }
    //提交订单控制器
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        //获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = this.orderFeignClient.submitSeckillOrder(orderInfo);
        if (orderId==null){
            //提示信息
            return Result.fail().message("下单失败");
        }
        //将真正的下单 保存到缓存
        this.redisTemplate.opsForHash().put(RedisConst.SECKILL_ORDERS_USERS,userId,orderId.toString());
        //删除预下单数据
        this.redisTemplate.opsForHash().delete(RedisConst.SECKILL_ORDERS,userId);
        return Result.ok(orderId);
    }
}
